//
//  JPPhotoViewController.m
//  Jpod
//
//  Created by zenox on 2022/3/31.
//

#import "JPPhotoViewController.h"

#import <TZImagePickerController/TZImagePickerController.h>
#import <CoreServices/CoreServices.h>

//#import "TYImagePicker.h"

#import <TZPhotoPreviewController.h>
#import <AssetsLibrary/AssetsLibrary.h>


///屏幕宽高
#define SCREEN_HEIGHT                            [UIScreen mainScreen].bounds.size.height
#define SCREEN_WIDTH                             [UIScreen mainScreen].bounds.size.width
///常规导航栏按钮大小
#define KDefualtNavItemSize                      CGSizeMake(44, 44)
#define  KNavBarHeight      ([UIDevice ty_fringeScreen] ? 88 : 64)
#define  KStatusHeight      ([UIDevice ty_fringeScreen] ? 44 : 20)
#define  KTabBarHeight      ([UIDevice ty_fringeScreen] ? 83 : 49)
#define  KSafeAreaHeight    34

@interface JPPhotoViewController ()<TZImagePickerControllerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>


@property (nonatomic,strong) UILabel *typeLable;

@property (nonatomic,strong) UIView *lineView;

/* 图片选择器 */
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;

/* 选取的图片资源数组 */
@property (nonatomic, strong) NSMutableArray <UIImage *> *imgArray;
/* 选择的定位 */
@property (strong, nonatomic) CLLocation *location;

@property (nonatomic, assign)BOOL netCommittingStatus;//YES 网络正在提交状态,防止重复提交

@property (nonatomic, strong) UIButton *sumbitBtn;


@end

@implementation JPPhotoViewController

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    NSLog(@"========touchesBegan========");
    
//    [self showAlertViewOld];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor redColor];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(100, 200, 50, 50);
    button.backgroundColor = [UIColor redColor];[button setTitle:@"照相" forState:UIControlStateNormal];
    
    [button addTarget:self action:@selector(btnClick1) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(100, 300, 50, 50);[button setTitle:@"录像" forState:UIControlStateNormal];
        button.backgroundColor = [UIColor redColor];
        [button addTarget:self action:@selector(btnClick2) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
    }
    
 
   
}

- (void)btnClick2{
    [self showAlertViewVideo];
    
}

- (void)btnClick1{
    [self showAlertViewPhoto];
    
}
- (NSMutableArray *)imgArray{
    if (!_imgArray) {
        _imgArray = [NSMutableArray array];
    }
    return _imgArray;
}

#pragma mark -
- (UIView *)getImageActionSheetView {
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 160 + KSafeAreaHeight)];
    bgView.backgroundColor = [UIColor whiteColor];
    {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn setTitle:@"相册" forState:UIControlStateNormal];
        btn.backgroundColor = [UIColor whiteColor];
        btn.frame = CGRectMake(0, 0, SCREEN_WIDTH, 50);
        [bgView addSubview:btn];
        [btn addTarget:self action:@selector(showUserAlbum) forControlEvents:UIControlEventTouchUpInside];
    }
    {
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 50.0, SCREEN_WIDTH, 0.5)];
        line.backgroundColor = [UIColor blackColor];
        [bgView addSubview:line];
    }
    {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn setTitle:@"拍照" forState:UIControlStateNormal];
        btn.backgroundColor = [UIColor whiteColor];
        btn.frame = CGRectMake(0, 50.5, SCREEN_WIDTH, 50);
        [bgView addSubview:btn];
        [btn addTarget:self action:@selector(takePhoto) forControlEvents:UIControlEventTouchUpInside];
    }
    {
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 100, SCREEN_WIDTH, 10)];
        line.backgroundColor = [UIColor blackColor];
        [bgView addSubview:line];
    }
    {
        UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn1 setTitle:@"取消" forState:UIControlStateNormal];
        btn1.frame = CGRectMake(0, 120, SCREEN_WIDTH, 50);
        btn1.backgroundColor = [UIColor whiteColor];
        [bgView addSubview:btn1];
        [btn1 addTarget:self action:@selector(cancelAction) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return bgView;
}

- (void)cancelAction {
}


- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(PHAsset *)asset{

    PHAsset *ast = (PHAsset *)asset;
  
     PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
     options.version = PHImageRequestOptionsVersionCurrent;
     options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
  
     PHImageManager *manager = [PHImageManager defaultManager];
  
     [manager requestAVAssetForVideo:ast options:options resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
  
         AVURLAsset *urlAsset = (AVURLAsset *)asset;
  
         NSURL *sourceURL = urlAsset.URL;
         
         NSLog(@" == %@",sourceURL);
         
//         NSURL *sourceURL = [info objectForKey:UIImagePickerControllerMediaURL];
         NSLog(@"%@",[NSString stringWithFormat:@"%f s", [self getVideoLength:sourceURL]]);
         NSLog(@"%@", [NSString stringWithFormat:@"%.2f kb", [self getFileSize:[sourceURL path]]]);
         NSURL *newVideoUrl ; //一般.mp4
         NSDateFormatter *formater = [[NSDateFormatter alloc] init];//用时间给文件全名，以免重复，在测试的时候其实可以判断文件是否存在若存在，则删除，重新生成文件即可
         [formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
         newVideoUrl = [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingFormat:@"/Documents/output-%@.mp4", [formater stringFromDate:[NSDate date]]]] ;//这个是保存在app自己的沙盒路径里，后面可以选择是否在上传后删除掉。我建议删除掉，免得占空间。
         [picker dismissViewControllerAnimated:YES completion:nil];
         [self convertVideoQuailtyWithInputURL:sourceURL outputURL:newVideoUrl completeHandler:nil];
    
  
     }];
    

    
}

- (NSString *)getBytesFromDataLength:(NSInteger)dataLength {
    NSString *bytes;
    if (dataLength >= 0.1 * (1024 * 1024)) {
        bytes = [NSString stringWithFormat:@"%0.1fM",dataLength/1024/1024.0];
    } else if (dataLength >= 1024) {
        bytes = [NSString stringWithFormat:@"%0.0fK",dataLength/1024.0];
    } else {
        bytes = [NSString stringWithFormat:@"%zdB",dataLength];
    }
    return bytes;
}


//随意提交


- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos{
    

    // 你可以通过一个asset获得原图，通过这个方法：[[TZImageManager manager] getOriginalPhotoWithAsset:completion:]
    // photos数组里的UIImage对象，默认是828像素宽，你可以通过设置photoWidth属性的值来改变它
    
    if (isSelectOriginalPhoto) {
        
        [[TZImageManager manager] getOriginalPhotoDataWithAsset:assets.lastObject completion:^(NSData *data, NSDictionary *info, BOOL isDegraded) {

            NSLog(@"%@",[self getBytesFromDataLength:data.length]);
            
        }];

    }
    
  
    
    

}
- (void)showUserAlbum:(BOOL)isPhoto{
    
    //确认相册访问权限
    [self isCanVisitPhotoLibrary:^(BOOL available) {
        if (available) {
            TZImagePickerController *pickerController = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
            if (isPhoto) {
                           pickerController.allowPickingOriginalPhoto = YES;
                           pickerController.allowTakeVideo = NO;
                           pickerController.allowTakePicture = NO;
                           pickerController.allowPickingImage = YES;
                           pickerController.allowPickingVideo = NO;

                       }else{
                           pickerController.allowPickingOriginalPhoto = NO;
                           pickerController.allowTakePicture = NO;
                           pickerController.allowTakeVideo = YES;
                           pickerController.allowPickingVideo = YES;
                           pickerController.allowPickingImage = NO;

                       }
            pickerController.modalPresentationStyle = UIModalPresentationFullScreen;

            [self presentViewController:pickerController animated:YES completion:nil];
        }
    }];
}

//相册权限检测
-(void)isCanVisitPhotoLibrary:(void(^)(BOOL))result {
    //请求权限
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusAuthorized) {
        result(YES);
        return;
    }
    if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
        result(NO);
        return ;
    }
    
    if (status == PHAuthorizationStatusNotDetermined) {
        
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            // 回调是在子线程的
            NSLog(@"%@",[NSThread currentThread]);
            dispatch_async(dispatch_get_main_queue(), ^{
                if (status != PHAuthorizationStatusAuthorized) {}
                  result(YES);
            });
        }];
    }
}

- (void)takePhoto {
    
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {} else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self takePhoto];
                });
            }
        }];
        // 拍照之前还需要检查相册权限
    } else if ([PHPhotoLibrary authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        /// 无相册权限时，也调用相机拍照功能
        [self pushImagePickerController];
    } else if ([PHPhotoLibrary authorizationStatus] == 0) { // 未请求过相册权限
        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
            [self takePhoto];
        }];
    } else {
        [self pushImagePickerController];
    }
}

- (void)takeVideo{
    
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {} else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self takeVideo];
                });
            }
        }];
        // 拍照之前还需要检查相册权限
    } else if ([PHPhotoLibrary authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        /// 无相册权限时，也调用相机拍照功能
        [self pushVedioPickerController];
    } else if ([PHPhotoLibrary authorizationStatus] == 0) { // 未请求过相册权限
        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
            [self takeVideo];
        }];
    } else {
        [self pushVedioPickerController];
    }
}

//获取视频的第一帧截图, 返回UIImage
//需要导入AVFoundation.h
- (UIImage*) getVideoPreViewImageWithPath:(NSURL *)videoPath
{
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoPath options:nil];
    
    AVAssetImageGenerator *gen         = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    gen.appliesPreferredTrackTransform = YES;
    
    CMTime time      = CMTimeMakeWithSeconds(0.0, 600);
    NSError *error   = nil;
    
    CMTime actualTime;
    CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *img     = [[UIImage alloc] initWithCGImage:image];
    
    return img;
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
 
    [picker dismissViewControllerAnimated:YES completion:nil];
}





- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
  [picker dismissViewControllerAnimated:YES completion:nil];
  NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //获取用户选择或拍摄的是照片还是视频
    NSString *mediaType = info[UIImagePickerControllerMediaType];
    
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        _imagePickerVc.delegate = nil;
        _imagePickerVc = nil;
      TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
      tzImagePickerVc.sortAscendingByModificationDate = NO;
      [tzImagePickerVc showProgressHUD];
      if ([type isEqualToString:@"public.image"]) {
          UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
          NSDictionary *meta = [info objectForKey:UIImagePickerControllerMediaMetadata];
          
          [self.imgArray addObject:image];
          
    //      [self.collectionView reloadData];
    //      self.imgCountLabel.text = [NSString stringWithFormat:@"%d/3",(int)self.imgArray.count];
          
          // save photo and get asset / 保存图片，获取到asset
          [[TZImageManager manager] savePhotoWithImage:image meta:meta location:self.location completion:^(PHAsset *asset, NSError *error){
              [tzImagePickerVc hideProgressHUD];
              if (error) {
                  NSLog(@"图片保存失败 %@",error);
              }
    //          else {
    //              [self.imgArray addObject:image];
    //              [self.collectionView reloadData];
    //              self.imgCountLabel.text = [NSString stringWithFormat:@"%d/3",(int)self.imgArray.count];
    //          }
          }];
       }
    }
    
    else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]) {
        
        if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
            
            //如果是拍摄的视频, 则把视频保存在系统多媒体库中
            NSLog(@"video path: %@", info[UIImagePickerControllerMediaURL]);
            
            ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
            [library writeVideoAtPathToSavedPhotosAlbum:info[UIImagePickerControllerMediaURL] completionBlock:^(NSURL *assetURL, NSError *error) {
                
                if (!error) {
                    
                    NSLog(@"视频保存成功");
                } else {
                    
                    NSLog(@"视频保存失败");
                }
            }];
        }
    }
 
}

- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.modalPresentationStyle = 0;
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
//        _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
//        _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (@available(iOS 9, *)) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        } else {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
            BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
 
    }
    return _imagePickerVc;
}

// 调用相机录像
- (void)pushVedioPickerController {
    // 提前定位
    __weak typeof(self) weakSelf = self;
    [[TZLocationManager manager] startLocationWithSuccessBlock:^(NSArray<CLLocation *> *locations) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.location = [locations firstObject];
    } failureBlock:^(NSError *error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.location = nil;
    }];
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        self.imagePickerVc.sourceType = sourceType;
        NSMutableArray *mediaTypes = [NSMutableArray array];

        [mediaTypes addObject:(NSString *)kUTTypeMovie];
        
        if (mediaTypes.count) {
            _imagePickerVc.mediaTypes = mediaTypes;
        }
        [self presentViewController:_imagePickerVc animated:YES completion:nil];
       
    } else {
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}
// 调用相机
- (void)pushImagePickerController {
    // 提前定位
    __weak typeof(self) weakSelf = self;
    [[TZLocationManager manager] startLocationWithSuccessBlock:^(NSArray<CLLocation *> *locations) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.location = [locations firstObject];
    } failureBlock:^(NSError *error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.location = nil;
    }];
    
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        self.imagePickerVc.sourceType = sourceType;
        NSMutableArray *mediaTypes = [NSMutableArray array];

        [mediaTypes addObject:(NSString *)kUTTypeImage];
  
        if (mediaTypes.count) {
            _imagePickerVc.mediaTypes = mediaTypes;
        }
        [self presentViewController:_imagePickerVc animated:YES completion:^{}];
       
    } else {
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}

// 调用相机
//- (void)pushImagePickerController {
//    // 提前定位
//    __weak typeof(self) weakSelf = self;
//    [[TZLocationManager manager] startLocationWithSuccessBlock:^(NSArray<CLLocation *> *locations) {
//        __strong typeof(weakSelf) strongSelf = weakSelf;
//        strongSelf.location = [locations firstObject];
//    } failureBlock:^(NSError *error) {
//        __strong typeof(weakSelf) strongSelf = weakSelf;
//        strongSelf.location = nil;
//    }];
//
////    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
////    self.imagePickerVc.allowsEditing = YES;
//
//    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
////        self.imagePickerVc.sourceType = sourceType;
////        NSMutableArray *mediaTypes = [NSMutableArray array];
////
////        [mediaTypes addObject:(NSString *)kUTTypeMovie];
//
//
//           self.imagePickerVc.sourceType = UIImagePickerControllerSourceTypeCamera;
//           self.imagePickerVc.cameraDevice = UIImagePickerControllerCameraDeviceRear;
//           self.imagePickerVc.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
//           self.imagePickerVc.videoQuality = UIImagePickerControllerQualityType640x480;
//           self.imagePickerVc.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
//           self.imagePickerVc.allowsEditing = YES;
//
////        if (mediaTypes.count) {
////            _imagePickerVc.mediaTypes = mediaTypes;
////        }
//        [self presentViewController:_imagePickerVc animated:YES completion:nil];
//
//    } else {
//        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
//    }
//}

- (void)showAlertViewPhoto{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *imageAlbumAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self showUserAlbum:YES];
    }];
    UIAlertAction *takePhotoAction = [UIAlertAction actionWithTitle:@"相机"  style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self takePhoto];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alertVC addAction:imageAlbumAction];
    [alertVC addAction:takePhotoAction];
    [alertVC addAction:cancelAction];
    
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)showAlertViewVideo{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *imageAlbumAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self showUserAlbum:NO];
    }];
    UIAlertAction *takeVideoAction = [UIAlertAction actionWithTitle:@"视频" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self takeVideo];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alertVC addAction:imageAlbumAction];
    [alertVC addAction:takeVideoAction];
    [alertVC addAction:cancelAction];
    
    [self presentViewController:alertVC animated:YES completion:nil];
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/



//此方法可以获取文件的大小，返回的是单位是KB。
- (CGFloat) getFileSize:(NSString *)path
{
NSLog(@"%@",path);
NSFileManager *fileManager = [NSFileManager defaultManager];
float filesize = -1.0;
if ([fileManager fileExistsAtPath:path]) {
NSDictionary *fileDic = [fileManager attributesOfItemAtPath:path error:nil];//获取文件的属性
unsigned long long size = [[fileDic objectForKey:NSFileSize] longLongValue];
filesize = 1.0*size/1024;
}else{
NSLog(@"找不到文件");
}
return filesize;
}

//此方法可以获取视频文件的时长。
- (CGFloat) getVideoLength:(NSURL *)URL
{

AVURLAsset *avUrl = [AVURLAsset assetWithURL:URL];
CMTime time = [avUrl duration];
int second = ceil(time.value/time.timescale);
return second;
}

- (void) convertVideoQuailtyWithInputURL:(NSURL*)inputURL
                       outputURL:(NSURL*)outputURL
                 completeHandler:(void (^)(AVAssetExportSession*))handler
{
AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:inputURL options:nil];

AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];
//  NSLog(resultPath);
exportSession.outputURL = outputURL;
exportSession.outputFileType = AVFileTypeMPEG4;
exportSession.shouldOptimizeForNetworkUse= YES;
[exportSession exportAsynchronouslyWithCompletionHandler:^(void)
{
 switch (exportSession.status) {
     case AVAssetExportSessionStatusCancelled:
         NSLog(@"AVAssetExportSessionStatusCancelled");
         break;
     case AVAssetExportSessionStatusUnknown:
         NSLog(@"AVAssetExportSessionStatusUnknown");
         break;
     case AVAssetExportSessionStatusWaiting:
         NSLog(@"AVAssetExportSessionStatusWaiting");
         break;
     case AVAssetExportSessionStatusExporting:
         NSLog(@"AVAssetExportSessionStatusExporting");
         break;
     case AVAssetExportSessionStatusCompleted:
         NSLog(@"AVAssetExportSessionStatusCompleted");
         NSLog(@"%@",[NSString stringWithFormat:@"%f s", [self getVideoLength:outputURL]]);
         NSLog(@"%@", [NSString stringWithFormat:@"%.2f kb", [self getFileSize:[outputURL path]]]);
         
         //UISaveVideoAtPathToSavedPhotosAlbum([outputURL path], self, nil, NULL);//这个是保存到手机相册
         
         [self alertUploadVideo:outputURL];
         break;
     case AVAssetExportSessionStatusFailed:
         NSLog(@"AVAssetExportSessionStatusFailed");
         break;
 }
 
}];
}


-(void)alertUploadVideo:(NSURL*)URL{
CGFloat size = [self getFileSize:[URL path]];
NSString *message;
NSString *sizeString;
CGFloat sizemb= size/1024;
if(size<=1024){
sizeString = [NSString stringWithFormat:@"%.2fKB",size];
}else{
sizeString = [NSString stringWithFormat:@"%.2fMB",sizemb];
}

if(sizemb<2){
[self uploadVideo:URL];
}
else if(sizemb<=5){
message = [NSString stringWithFormat:@"视频%@，大于2MB会有点慢，确定上传吗？", sizeString];
UIAlertController * alertController = [UIAlertController alertControllerWithTitle: nil
                                                                          message: message
                                                                   preferredStyle:UIAlertControllerStyleAlert];


[alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
    [[NSFileManager defaultManager] removeItemAtPath:[URL path] error:nil];//取消之后就删除，以免占用手机硬盘空间（沙盒）
}]];
[alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
    [self uploadVideo:URL];
}]];
[self presentViewController:alertController animated:YES completion:nil];


}/*else if(sizemb>5){
message = [NSString stringWithFormat:@"视频%@，超过5MB，不能上传，抱歉。", sizeString];
UIAlertController * alertController = [UIAlertController alertControllerWithTitle: nil
                                                                          message: message
                                                                   preferredStyle:UIAlertControllerStyleAlert];

[alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
    [[NSFileManager defaultManager] removeItemAtPath:[URL path] error:nil];//取消之后就删除，以免占用手机硬盘空间
    
}]];
[self presentViewController:alertController animated:YES completion:nil];

}
*/

}

-(void)uploadVideo:(NSURL*)URL{


NSData *data = [NSData dataWithContentsOfURL:URL];

//    [Manage requestToUploadAttachmentsDataWith:^(NSDictionary *base) {
//        if ([base[@"errno"] intValue] == 200) {
//            [SVProgressHUD showInfoWithStatus:[base objectForKey:@"err"]];
//        }else{
//            [SVProgressHUD showInfoWithStatus:[base objectForKey:@"err"]];
//        }
//    } taskId:self.taskId fileImg:nil URL:URL enclosureType:self.taskId fileVideo:data];
}

- (void)reSizeImageData:(UIImage *)sourceImage maxImageSize:(CGFloat)maxImageSize{
    
    NSData *imageData1 = UIImageJPEGRepresentation(sourceImage,1.0);

    if (maxImageSize <= 0.0) maxImageSize = 1024.0;
 
    //先调整分辨率
    CGSize newSize = CGSizeMake(sourceImage.size.width, sourceImage.size.height);
 
    CGFloat tempHeight = newSize.height / maxImageSize;
    CGFloat tempWidth = newSize.width / maxImageSize;
 
    if (tempWidth > 1.0 && tempWidth > tempHeight) {
        newSize = CGSizeMake(sourceImage.size.width / tempWidth, sourceImage.size.height /     tempWidth);
    }else if (tempHeight > 1.0 && tempWidth < tempHeight){
        newSize = CGSizeMake(sourceImage.size.width / tempHeight, sourceImage.size.height / tempHeight);
    }
 
    UIGraphicsBeginImageContext(newSize);
    [sourceImage drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
 
    NSData *imageData2 = UIImageJPEGRepresentation(newImage,1.0);

    //调整大小
    NSData *imageData = UIImageJPEGRepresentation(sourceImage,1.0);
    CGFloat sizeOriginKB = imageData.length / 1024.0;
 
    if (sizeOriginKB > 5000) {/// 5MB 模糊为5000kb
        dispatch_async(dispatch_get_main_queue(), ^{
//            [self makeToast:@"图片格式或大小不符，请重新上传"];
        });
    }else{
    
//    NSString *name = [NSString stringWithFormat:@"pic%@.%@",[self getImageNameBaseCurrentTime],[self getImageTypeWithData:imageData]];
//    [self submitImageFileData:imageData andImageName:name type:[self getImageTypeWithData:imageData]];
    }
}


@end
